#include "gffreader.h"

GffReader::GffReader(QString gffFileName, QObject *parent) :
    gffFileName(gffFileName), QObject(parent)
{

}

void GffReader::process()
{
    QFile gff(gffFileName);

    if( !gff.exists() )
    {
        qDebug() << "file not found." << endl;
        return;
    }

    if( ! gff.open(QIODevice::ReadOnly))
    {
        qDebug() << "file " << gffFileName << " can't be opened." << endl;
        return;
    }
    qDebug() << "file " << gffFileName << " opened." << endl;

    //this is for csv files... works for now
    QTextStream inStream(&gff);
    QString line;
    do {
        line = inStream.readLine();
        //qDebug() << "line = " << line << endl;

        if( ! line.startsWith("#") && line.size() > 8 )//why 8?  8 tabs at least.  Not best solution
        {
            //divide line into major tokens- by the tab delim
           QStringList majorTokens = line.split("\t", QString::SkipEmptyParts);
           QString seqId;
           QString source;
           QString type;
           int start;
           int stop;
           bool posStrand;

           if( majorTokens.size() < 7 )
           {
               qDebug() << "Processing gff file failed on file: " << gffFileName << endl;
               qDebug() << "     on line: " << line << endl;
               exit(-1);
           }

           processFirstColumnsInLine( majorTokens, seqId, source, type, start, stop, posStrand);

           //emit( dataPacketGenerated( new GenomeElementDataPacket()) );
        }
    } while (!inStream.atEnd() );

}

void GffReader::processFirstColumnsInLine( QStringList tokens, QString& seqId, QString& source, QString& type, int& start, int& stop, bool& posStrand )
{

    seqId = tokens[0];
    source = tokens[1];
    type = tokens[2];
    start = tokens[3].toInt();
    stop = tokens[4].toInt();
    //skipping score - 5th token
    QString strand = tokens[6];
    if( strand.contains("+") )
        posStrand = true;
    else
        posStrand = false;
    //skipping phase - 7th token
}
